import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getProfile, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
// 暴露子仓库的实例对象
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state, token) {
      state.token = ''
      removeToken()
    },
    // 设置用户信息
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    reomveUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 发送请求获取token,存储到vuex
    async userLogin(context, loginForm) {
      console.log(context)
      const res = await login(loginForm)
      console.log(res.data, 123123123)
      context.commit('updateToken', res.data)
    },
    // 获取用户信息,存储到vuex
    async getUserInfo(context) {
      try {
        // ajax获取数据
        const res = await getProfile()
        console.log('用来获取用户信息的,', res)
        context.commit('updateUserInfo', res.data)
        const info = await getUserDetailById(res.data.userId)
        context.commit('updateUserInfo', { ...info.data, ...res.data })
        return res.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    // 清空用户信息
    logout(context) {
      context.commit('removeToken')
      context.commit('reomveUserInfo')
      resetRouter()
    }
  }
}
